package com.cow.framework.utils.string;

/**
 * 
 * 字节数值与字符串的转换
 * 
 * @author hehzh
 * @since 2014-10-16
 * @version 1.0
 *
 */
public class Byte2HexStr {

	private Byte2HexStr(){}
	
	/**
	 * 字节数组转换成16进制字符串,不含空格
	 * @param b 字节数组
	 * @return 字节数组转换成16进制字符串,不含空格
	 */
	public static String parse(byte[] b) {
		return parse(b,false);
	}
	
	/**
	 * 字节数组转换成16进制字符串，可选择各个字节是否用空格分开
	 * @param b 字节数组
	 * @param isWithSpace 各个字节是否用空格分开, true表示用空格分开
	 * @return 字节数组转换成16进制字符串
	 */
	public static String parse(byte[] b,boolean isWithSpace) {
		if(null==b || b.length<=0) return "";
		StringBuffer sb = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) stmp = "0" + stmp;
			if (isWithSpace) stmp = stmp + " ";
			sb.append(stmp);
		}
		String ret = sb.toString().toUpperCase();
		if(isWithSpace)
		{
			return ret.substring(0,ret.length()-1);
		}
		else
		{
			return ret;
		}
	}
	

	/**
	 * 16进制字符串转换成字节数组 ：例如"02AB09"==>{0x02,0xAB,0x09}
	 * @param str 不带空格的16进制字符串,例如"02AB09"
	 * @return 字节数组
	 * @throws Exception 失败时抛出异常
	 */
	public static byte[] Str2byte(String str) throws Exception{
		byte[] b = str.getBytes();
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}
}
